package com.wanjia.estate.controller;

import cn.hutool.core.util.RandomUtil;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.graphics.PdfImageType;
import com.wanjia.estate.constant.DocumentType;
import com.wanjia.estate.constant.tex.Status;
import com.wanjia.estate.exception.ControllerException;
import com.wanjia.estate.pojo.model.JsonResult;
import com.wanjia.estate.pojo.ocr.OcrResponse;
import com.wanjia.estate.pojo.tax.*;
import com.wanjia.estate.properties.FolderPathProperties;
import com.wanjia.estate.service.TaxShiftService;
import com.wanjia.estate.service.httpservice.OcrHttpService;
import com.wanjia.estate.service.httpservice.TaxHttpService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;

import static com.wanjia.estate.constant.tex.Status.*;

@RestController
@RequestMapping("/tax")
@Tag(name = "税务业务控制器")
@Slf4j
public class TaxController extends BaseController {

    @Setter(onMethod_ = @Autowired)
    private FolderPathProperties properties;

    @Autowired
    TaxHttpService taxHttpService;

    @Autowired
    TaxShiftService taxShiftService;

    @Autowired
    OcrHttpService ocrHttpService;

    @Value("${nsh.test:false}")
    private Boolean nsh;

    /**
     * 推送税务业务A001
     *
     * @param request
     * @return
     */
    @PostMapping("/report")
    @Operation(summary = "开启税务业务A001")
    public JsonResult<A001.Rwjshouselist> report(@RequestBody A001.RequestOne request) throws ParseException, FileNotFoundException {
//        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

        A001.RequestRwjshouselist rwjshouselist = request.getTaxbizml().getRwjshouselist();
        //全局数据补全
        rwjshouselist.getHousevo().setSjrq(new Date());
        //交易方信息数据补全
        List<A001.Jyfxx> jyfxx = rwjshouselist.getJyfxx();
        for (A001.Jyfxx jyfxx1 : jyfxx) {
            jyfxx1.setDz("镇江");
            jyfxx1.setScqdfwsj(new Date());
        }
        //房源基本信息
        rwjshouselist.getFyjbxx().setFyxxly("3");
        rwjshouselist.getFyjbxx().setJdxzdm("321112002");
        rwjshouselist.getFyjbxx().setTdsybh("镇江");
        rwjshouselist.getFyjbxx().setFwzh("1");
        rwjshouselist.getFyjbxx().setDyh("1");
        rwjshouselist.getFyjbxx().setDlmc("镇江");
        rwjshouselist.getFyjbxx().setTnmj(BigDecimal.ZERO);
        rwjshouselist.getFyjbxx().setGlmj(BigDecimal.ZERO);
        rwjshouselist.getFyjbxx().setCcsmj(BigDecimal.ZERO);
        rwjshouselist.getFyjbxx().setZxcckmj(BigDecimal.ZERO);
        rwjshouselist.getFyjbxx().setCkmj(BigDecimal.ZERO);
        //房产交易信息
        rwjshouselist.getFcjycjxx().setFcjyfsdm("01");
        rwjshouselist.getFcjycjxx().setTdzsskccb(BigDecimal.valueOf(0));
        rwjshouselist.getFcjycjxx().setDqyskje(BigDecimal.valueOf(0));
        rwjshouselist.getFcjycjxx().setGrsdskchlfy(BigDecimal.valueOf(0));
        rwjshouselist.getFcjycjxx().setQsqszylbdm("21");
        rwjshouselist.getFcjycjxx().setQsqszydxdm("20106");
        rwjshouselist.getFcjycjxx().setQsqszyytdm("201");
        rwjshouselist.getFcjycjxx().setJyjg(BigDecimal.ZERO);
        rwjshouselist.getFcjycjxx().setDj(BigDecimal.ZERO);
        rwjshouselist.getFcjycjxx().setWbjyjg(BigDecimal.ZERO);
        rwjshouselist.getFcjycjxx().setBcsbjysfsyzrfzkp("1");
        rwjshouselist.getFcjycjxx().setBcjydfzzsslhzsl(BigDecimal.ZERO);
        rwjshouselist.getFcjycjxx().setDqysskssyf("8");
//        rwjshouselist.getFcjycjxx().setHtqdrq(new Date());
        rwjshouselist.getFcjycjxx().setQsdjrq(new Date());


        if(nsh){
            if (rwjshouselist.getZlffpxx().getFphm().isEmpty()||rwjshouselist.getZlffpxx().getFpdm().isEmpty()){
                rwjshouselist.getZlffpxx().setFpdm("032002200205");
                rwjshouselist.getZlffpxx().setFphm("05409114");
            }
        } else {
            String fpdm1 = rwjshouselist.getZlffpxx().getFpdm();
            String fphm1 = rwjshouselist.getZlffpxx().getFphm();
            if (fphm1 == null || fpdm1 == null) {
                String pdfpath = properties.getPdfpath();
                String dir = DocumentType.get("invoice").dir();
                String invoicePath = pdfpath + dir;
                File folder = new File(invoicePath);
                File[] files = folder.listFiles();
                if (files == null) {
                    throw new ControllerException("发票文件不存在");
                }
                String fpdm = null;
                String fphm = null;
                for (File file : files) {
                    OcrResponse ocrResponse;
                    try {
                        ocrResponse = ocrHttpService.ocrScan(file);
                    } catch (Exception e) {
                        log.error("识别服务调用异常", e);
                        continue;
                    }
                    String message = ocrResponse.getMessage();
                    String[] split = message.split(",", 5);
                    fpdm = split[2];
                    fphm = split[3];
                }

                rwjshouselist.getZlffpxx().setFpdm(fpdm);
                rwjshouselist.getZlffpxx().setFphm(fphm);
            } else {
                rwjshouselist.getZlffpxx().setFpdm(fpdm1);
                rwjshouselist.getZlffpxx().setFphm(fphm1);
            }

        }

        //调用A001申请税务审核
        A001.Response response = taxHttpService.a001(request);


//        // 轮询A010查询审核结果
//        for (int i = 0; i < 36; i++) {
//            Status status = queryStatus(STATUS01, STATUS40, STATUS00);
//            log.debug("轮询查询状态: {}", status);
//            switch (status) {
//                case STATUS40:
//                    // 审核通过
//                    return new JsonResult<>(OK, true);
//                case STATUS00:
//                case STATUS10:
//                case STATUS11:
//                case STATUS12:
//                case STATUS13:
//                    // 中间状态，继续轮询
//                    try {
//                        Thread.sleep(5000);
//                    } catch (InterruptedException e) {
//                        log.warn("睡眠异常", e);
//                    }
//                    continue;
//                default:
//                    // 异常状态，意外中断
//                    return new JsonResult<>(OK, false);
//            }
//        }
        return new JsonResult<>(OK, response.getTaxbizml().getRwjshouselist());
    }


    /**
     * 推送税务电子材料数据A006
     *
     * @param request
     * @return
     */
    @PostMapping("/report/dzcl")
    @Operation(summary = "推送税务电子材料A006")
    public JsonResult<List<A006.Yxzlxxjslist>> reportDzcl(@RequestBody A006.RequestSix request) throws IOException {
        //根据request找材料
        List<A006.RequestYxzlxxjslist> yxzlxxjslist = request.getTaxbizml().getYxzlxxjslist();
        for (A006.RequestYxzlxxjslist requestYxzlxxjslist : yxzlxxjslist) {
            requestYxzlxxjslist.setSjrq(new Date());
            List<A006.YXWJXX> yxwjxx = requestYxzlxxjslist.getYxwjxx();
            try {
                for (A006.YXWJXX yxwjxx1 : yxwjxx) {
                    String yxwjmc = yxwjxx1.getYxwjmc();//获取影像文件名称
                    A006.YXWJXX yxwjxx2 = taxShiftService.yxwjxxAddData(yxwjmc);
                    yxwjxx1.setZldm(yxwjxx2.getZldm());
                    yxwjxx1.setYxwjbh(yxwjxx2.getYxwjbh());
                    yxwjxx1.setYxwjfilename(yxwjxx2.getYxwjfilename());
                    yxwjxx1.setYxwjlx(yxwjxx2.getYxwjlx());
                    yxwjxx1.setSfbb(yxwjxx2.getSfbb());
                    yxwjxx1.setYxwjdz(yxwjxx2.getYxwjdz());
                }
            } catch (IOException e) {
                throw new RuntimeException("电子材料上传失败");
            }
        }
        A006.Response response = taxHttpService.a006(request);
        return new JsonResult<>(OK, response.getTaxbizml().getYxzlxxjslist());
    }


    /**
     * 查询税务状态A010
     *
     * @param request
     * @return
     */
    @PostMapping("/report/status")
    @Operation(summary = "查询税务状态A010")
    public JsonResult<List<A010.ResponseSbztxxlist>> reportStatus(@RequestBody A010.RequestTen request) {
        A010.Response response = taxHttpService.a010(request);
        return new JsonResult<>(OK, response.getTaxbizml().getSbztxxlist());

    }

    /**
     * 获取申报表A014
     *
     * @param request
     * @return
     */
    @PostMapping("/report/getPdf")
    @Operation(summary = "获取申报表A014")
    public JsonResult<Object> getReportPdf(@RequestBody A014.RequestFourteen request) throws IOException {
        A014.Response response = taxHttpService.a014(request);
        List<String> list = taxShiftService.base64PdfToPathService(response);
        List<PdfFile> pdfFileList = new ArrayList<>();
        for (String filepath : list) {
            PdfFile pdfFile = new PdfFile(
                    properties.getNginxpath() + filepath,
                    properties.getPdfpath() + filepath
            );
            pdfFileList.add(pdfFile);
        }
        return new JsonResult<>(OK, pdfFileList);
    }


    /**
     * 申报表签名发送A015
     *
     * @param request
     * @return
     */
    @PostMapping("/report/pdf")
    @Operation(summary = "申报表签名发送A015")
    public JsonResult<List<A015.Fcjysbqrxxlist>> postReportPdf(@RequestBody A015.RequestFifteen request) throws IOException {
        extracted(request);
        A015.Response response = taxHttpService.a015(request);
        return new JsonResult<>(OK, response.getTaxbizml().getFcjysbqrxxlist());
    }

    private void extracted(A015.RequestFifteen request) throws IOException {
//        List<A015.RequestRcjysbqrxxlist> fcjysbqrxxlist = request.getTaxbizml().getFcjysbqrxxlist();
//        A015.RequestRcjysbqrxxlist requestRcjysbqrxxlist = fcjysbqrxxlist.get(0);
        List<A015.Fcjysbqrfjxxlist> fcjysbqrfjxxlist = request.getTaxbizml().getFcjysbqrfjxxlist();
        A015.Fcjysbqrfjxxlist yxwj = fcjysbqrfjxxlist.get(0);
        File file = new File(properties.getPdfpath() + "wjsj/" + "zlf.pdf");
        try (FileInputStream inputStream = new FileInputStream(file)) {
            byte[] bytes = new byte[(int) file.length()];
            inputStream.read(bytes);
            yxwj.setZldm("0201");
            yxwj.setYxwjbh("1");
            yxwj.setYxwjfilename("增量房交易申报单");
            yxwj.setYxwjlx("PDF");
            yxwj.setSfbb("1");
            yxwj.setYxwjdz("data:application/pdf;base64," + Base64.getEncoder().encodeToString(bytes));
        }

    }

    /**
     * 自动申报A023
     *
     * @param request
     * @return
     */
    @PostMapping("/report/auto")
    @Operation(summary = "自动申报A023")
    public JsonResult<List<A023.ResponseFcjysbxxlistThree>> reportAutoPdf(@RequestBody A023.RequestTwentyThree request) {
        A023.Response response = taxHttpService.a023(request);
        return new JsonResult<>(OK, response.getTaxbizml().getFcjysbxxlist());

    }

    /**
     * 获取待缴款列表A017
     *
     * @param request
     * @return
     */
    @PostMapping("/report/getList")
    @Operation(summary = "获取待缴款列表A017")
    public JsonResult<A017.TaxbizmlSeventeen> postReportList(@RequestBody A017.RequestSeventeen request) {
        A017.Response response = taxHttpService.a017(request);
        return new JsonResult<>(OK, response.getTaxbizml());

    }

    /**
     * 获取缴款二维码缴款A018
     *
     * @param request
     * @return
     */
    @PostMapping("/report/getQr")
    @Operation(summary = "获取缴款二维码缴款A018")
    public JsonResult<A018.TaxbizmlEighteen> reportQr(@RequestBody A018.RequestEighteen request) {
        A018.Response response = taxHttpService.a018(request);
        String ewm = response.getTaxbizml().getKkewm().getEwm();
        String qr = "data:application/jpg;base64," + ewm;
        response.getTaxbizml().getKkewm().setEwm(qr);
        return new JsonResult<>(OK, response.getTaxbizml());

    }


    /**
     * 查询缴款结果A019
     *
     * @param request
     * @return
     */
    @PostMapping("/report/getResult")
    @Operation(summary = "查询缴款结果A019")
    public JsonResult<A019.TaxbizmlNineteen> reportResult(@RequestBody A019.RequestNineteen request) {
        //TODO 调用A019查询缴款结果
        A019.Response response = taxHttpService.a019(request);


        return new JsonResult<>(OK, response.getTaxbizml());

    }


    /**
     * 获取完税证明A020
     *
     * @return
     */
    @PostMapping("/tax/pdf")
    @Operation(summary = "获取完税证明A020")
    public JsonResult<Object> getTexPdf(@RequestBody A020.RequestTwenty request) throws IOException {
        //TODO 调用A020获取完税证明
        A020.Response response = taxHttpService.a020(request);
        String s = taxShiftService.wszmPathService(response);

        //实例化PdfDocument类的对象
        PdfDocument pdf = new PdfDocument();

        //加载PDF文档
        pdf.loadFromFile(properties.getPdfpath() + s);

        File folder = new File(properties.getPdfpath() + "完税证明/");
        if (!folder.exists()) {
            folder.mkdir();
        }

        //遍历PDF每一页，保存为图片
        for (int i = 0; i < pdf.getPages().getCount(); i++) {
            //将页面保存为图片，并设置DPI分辨率
            BufferedImage image = pdf.saveAsImage(i, PdfImageType.Bitmap, 500, 500);
            //将图片保存为png格式
            File file = new File(folder, i + ".png");
            ImageIO.write(image, "PNG", file);
        }
        pdf.close();

        return new JsonResult<>(OK, new PdfFile(
                properties.getNginxpath() + s,
                properties.getPdfpath() + s
        ));
    }

    /**
     * 中途终止交易A003
     *
     * @return
     */
    @DeleteMapping("/shutdown")
    @Operation(summary = "中途终止交易A003")
    public JsonResult<List<A003.RwjshouselistThree>> stop(@RequestBody A003.RequestThree request) {
        //TODO 调用A003中途终止交易
        A003.Response response = taxHttpService.a003(request);
        return new JsonResult<>(OK, response.getTaxbizml().getRwjshouselist());

//        return new JsonResult<>(OK, true);
    }


    /**
     * 将登簿办证信息通过推送到税务端A011
     *
     * @param request
     * @return
     */
    @PostMapping("/report/book")
    @Operation(summary = "将登簿办证信息通过推送到税务端A011")
    public JsonResult<List<A011.Bdcdyhsjlist>> reportBook(@RequestBody A011.RequestEleven request) {
        //TODO 调用A011将登簿办证信息通过推送到税务端
        A011.Response response = taxHttpService.a011(request);
//        A011.Bdcdyhsjlist bdcdyhsjlist = response.getTaxbizml().getBdcdyhsjlist().get(0);
//        //暂时写死
//        bdcdyhsjlist.setFhm("0");
        return new JsonResult<>(OK, response.getTaxbizml().getBdcdyhsjlist());
    }

    /**
     * 计税的格式化数据信息A004
     *
     * @param request
     * @return
     */
    @PostMapping("/report/information")
    @Operation(summary = "计税的格式化数据信息A004")
    public JsonResult<A004.ResponseTaxbizml> reportInformation(@RequestBody A004.RequestFour request) {

        A004.Response response = taxHttpService.a004(request);
        return new JsonResult<>(OK, response.getTaxbizml());

    }


//    /**
//     * 状态查询，参数后续替换为真实查询参数
//     *
//     * @param s1 随机失败状态
//     * @param s2 随机成功状态
//     * @param s3 随机等待状态
//     * @return 当前税务状态，目前为s1,s2,s3随机
//     */
//    private Status queryStatus(Status s1, Status s2, Status s3) {
//        //TODO 目前为随机等待/成功/失败，后续替换为A010查询
//        int statusInt = RandomUtil.randomInt(9);
//        switch (statusInt) {
//            case 0:
//                return s1;
//            case 1:
//            case 2:
//            case 3:
//                return s2;
//            default:
//                return s3;
//        }
//    }
}
